<template>
  <div class="email-task-container">
    <el-row :gutter="20">
      <!-- Left: Task List -->
      <el-col :xs="24" :sm="24" :md="16" :lg="16">
        <el-card shadow="hover" class="task-list-card">
          <div slot="header" class="card-header">
            <div class="header-title">
              <i class="el-icon-s-order"></i>
              <span>邮件任务列表</span>
            </div>
          </div>
          <el-form :model="queryParams" ref="queryForm" size="small" :inline="true" v-show="showSearch">
             <el-form-item prop="taskName">
                <el-input v-model="queryParams.taskName" placeholder="搜索任务名称" clearable @keyup.enter.native="handleQuery" />
             </el-form-item>
             <el-form-item prop="subject">
                <el-input v-model="queryParams.emailSubject" placeholder="搜索邮件主题" clearable @keyup.enter.native="handleQuery" />
             </el-form-item>
             <el-form-item>
                <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
                <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
             </el-form-item>
          </el-form>

          <el-table v-loading="loading" :data="taskList" @row-click="handleRowClick">
            <el-table-column label="序号" type="index" width="50" align="center" />
            <el-table-column label="任务编号" prop="taskId" show-overflow-tooltip />
            <el-table-column label="任务名称" prop="taskName" show-overflow-tooltip />
            <el-table-column label="邮件主题" prop="emailSubject" show-overflow-tooltip />
            <el-table-column label="任务状态" align="center" width="100">
                <template slot-scope="scope">
                    <el-tag :type="getStatusType(scope.row.taskStatus)">{{ getStatusText(scope.row.taskStatus) }}</el-tag>
                </template>
            </el-table-column>
            <el-table-column label="发送时间" prop="scheduledTime" width="160" align="center">
                <template slot-scope="scope">{{ parseTime(scope.row.scheduledTime, '{y}-{m}-{d} {h}:{i}') }}</template>
            </el-table-column>
            <el-table-column label="接收数/成功/失败" align="center" width="150">
              <template slot-scope="scope">
                <span class="stat-number">{{ scope.row.totalCount || 0 }}</span> /
                <span class="stat-number success">{{ scope.row.successCount || 0 }}</span> /
                <span class="stat-number error">{{ scope.row.failCount || 0 }}</span>
              </template>
            </el-table-column>
            <el-table-column label="操作" width="100" align="center">
              <template slot-scope="scope">
                <el-button size="mini" type="text" icon="el-icon-delete" @click.stop="handleDelete(scope.row)">删除</el-button>
              </template>
            </el-table-column>
          </el-table>
          <pagination v-show="total>0" :total="total" :page.sync="queryParams.pageNum" :limit.sync="queryParams.pageSize" @pagination="getList" />

          <!-- 接收者列表 -->
          <div class="recipients-section" v-if="selectedTask">
            <div class="section-title">
              <div class="section-title-left">
                <i class="el-icon-user"></i>
                <span>{{ selectedTask.taskName }} 的接收者列表</span>
              </div>
              <el-tag type="info" size="small" v-if="taskRecipients && taskRecipients.length > 0">{{ taskRecipients.length }}个接收者</el-tag>
            </div>

            <div v-if="taskRecipients && taskRecipients.length > 0">
              <el-table
                :data="taskRecipients"
                border
                stripe
                size="small"
                style="width: 100%"
                height="300"
                class="recipients-table"
              >
                <el-table-column label="序号" type="index" width="50" align="center" />
                <el-table-column label="邮箱地址" prop="email" min-width="200" show-overflow-tooltip />
                <el-table-column label="联系人姓名" prop="customerName" width="120" show-overflow-tooltip />
                <el-table-column label="发送状态" prop="status" width="100" align="center">
                  <template slot-scope="scope">
                    <el-tag :type="getRecipientStatusType(scope.row.status)" size="mini">
                      {{ getRecipientStatusText(scope.row.status) }}
                    </el-tag>
                  </template>
                </el-table-column>
                <el-table-column label="发送时间" prop="sendTime" width="160" align="center">
                  <template slot-scope="scope">
                    <span>{{ parseTime(scope.row.sendTime, '{y}-{m}-{d} {h}:{i}') || '-' }}</span>
                  </template>
                </el-table-column>
                <el-table-column label="错误信息" prop="errorMsg" min-width="150" show-overflow-tooltip>
                  <template slot-scope="scope">
                    <span class="error-msg" v-if="scope.row.errorMsg">{{ scope.row.errorMsg }}</span>
                    <span v-else>-</span>
                  </template>
                </el-table-column>
              </el-table>
            </div>
            <div v-else class="empty-recipients">
              <i class="el-icon-message"></i>
              <span>暂无接收者数据</span>
            </div>
          </div>
        </el-card>
      </el-col>

      <!-- Right: Task Details -->
      <el-col :xs="24" :sm="24" :md="8" :lg="8">
        <el-card shadow="hover" class="task-detail-card">
           <div slot="header" class="card-header">
             <div class="header-title">
               <i class="el-icon-document-copy"></i>
               <span>任务详情</span>
             </div>
           </div>
           <div v-if="selectedTask">
              <div class="task-detail-header">
                <el-button type="text" icon="el-icon-refresh" @click="refreshTaskDetail" size="small">刷新详情</el-button>
              </div>
              <el-descriptions :column="1" border>
                <el-descriptions-item label="任务名称">{{ selectedTask.taskName }}</el-descriptions-item>
                <el-descriptions-item label="邮件主题">{{ selectedTask.emailSubject }}</el-descriptions-item>
                <el-descriptions-item label="任务状态">
                    <el-tag :type="getStatusType(selectedTask.taskStatus)">{{ getStatusText(selectedTask.taskStatus) }}</el-tag>
                </el-descriptions-item>
                <el-descriptions-item label="计划发送时间">{{ parseTime(selectedTask.scheduledTime, '{y}-{m}-{d} {h}:{i}:{s}') || '立即发送' }}</el-descriptions-item>
                <el-descriptions-item label="实际发送时间">{{ parseTime(selectedTask.sendTime, '{y}-{m}-{d} {h}:{i}:{s}') || '未发送' }}</el-descriptions-item>
                <el-descriptions-item label="发送完成时间">{{ parseTime(selectedTask.completeTime, '{y}-{m}-{d} {h}:{i}:{s}') || '未完成' }}</el-descriptions-item>
                <el-descriptions-item label="发送统计">
                  <div class="send-stats">
                    <span class="stat-item">
                      <span class="stat-label">总接收人数：</span>
                      <span class="stat-value">{{ selectedTask.totalRecipients || 0 }}</span>
                    </span>
                    <span class="stat-item">
                      <span class="stat-label">发送成功：</span>
                      <span class="stat-value success">{{ selectedTask.successCount || 0 }}</span>
                    </span>
                    <span class="stat-item">
                      <span class="stat-label">发送失败：</span>
                      <span class="stat-value error">{{ selectedTask.failCount || 0 }}</span>
                    </span>
                  </div>
                </el-descriptions-item>
                <el-descriptions-item label="创建人">{{ selectedTask.createUserName || selectedTask.createdBy }}</el-descriptions-item>
              </el-descriptions>
              <div class="html-preview">
                <h4>内容预览</h4>
                <div v-html="selectedTask.content" class="preview-box"></div>
              </div>
           </div>
           <div v-else class="empty-state">
             <i class="el-icon-info"></i>
             <p>从左侧列表选择一个任务查看详情</p>
           </div>
        </el-card>
      </el-col>
    </el-row>
  </div>
</template>

<script>
import { listEmailTask, getEmailTask, delEmailTask } from '@/api/email/emailTask'; // Assuming these API functions exist

export default {
  name: "EmailBulkTask",
  data() {
    return {
      loading: true,
      showSearch: true,
      taskList: [],
      total: 0,
      queryParams: {
        pageNum: 1,
        pageSize: 10,
        taskName: null,
        subject: null,
      },
      selectedTask: null,
      taskRecipients: [],
    };
  },
  created() {
    this.getList();
  },
  methods: {
    getList() {
      this.loading = true;
      this.queryParams.createUserid = this.$store.getters.userId;
      listEmailTask(this.queryParams).then(response => {
        this.taskList = response.rows;
        this.total = response.total;
        this.loading = false;
      });
    },
    handleQuery() {
      this.queryParams.pageNum = 1;
      this.getList();
    },
    resetQuery() {
      this.$refs.queryForm.resetFields();
      this.handleQuery();
    },
    handleRowClick(row) {
      this.selectedTask = row;
      this.getTaskRecipients(row.taskId);
    },
    getTaskRecipients(taskId) {
      getEmailTask(taskId).then(response => {
        this.selectedTask = response.data;
        this.taskRecipients = response.data.recipients || [];
      });
    },
    refreshTaskDetail() {
      if (this.selectedTask && this.selectedTask.taskId) {
        this.getTaskRecipients(this.selectedTask.taskId);
      }
    },
    handleDelete(row) {
      console.log('准备删除任务:', row);
      this.$modal.confirm('是否确认删除任务名称为"' + row.taskName + '"的数据项？').then(() => {
        console.log('用户确认删除，调用API删除任务ID:', row.taskId);
        return delEmailTask(row.taskId);
      }).then((response) => {
        console.log('删除API响应:', response);
        this.getList();
        this.$modal.msgSuccess("删除成功");
        if (this.selectedTask && this.selectedTask.taskId === row.taskId) {
          this.selectedTask = null;
          this.taskRecipients = [];
        }
      }).catch((error) => {
        console.error('删除失败详细信息:', error);
        if (error.response) {
          console.error('错误响应状态:', error.response.status);
          console.error('错误响应数据:', error.response.data);
          this.$modal.msgError(`删除失败: ${error.response.data.msg || error.response.statusText}`);
        } else if (error.request) {
          console.error('请求失败:', error.request);
          this.$modal.msgError("网络请求失败，请检查网络连接");
        } else {
          console.error('其他错误:', error.message);
          this.$modal.msgError(`删除失败: ${error.message}`);
        }
      });
    },
    getStatusType(status) {
      const statusMap = { '0': 'info', '1': 'primary', '2': 'warning', '3': 'success','4': 'danger' };
      return statusMap[status] || 'info';
    },
    getStatusText(status) {
      const statusMap = { '0': '草稿', '1': '待发送', '2': '发送中', '3': '已完成', '4': '已取消', };
      return statusMap[status] || '未知';
    },
    getRecipientStatusType(status) {
      switch (status) {
        case '0':
          return 'info';
        case '1':
          return 'warning';
        case '2':
          return 'success';
        case '3':
          return 'danger';
        default:
          return 'info';
      }
    },
    getRecipientStatusText(status) {
      switch (status) {
        case '0':
          return '未发送';
        case '1':
          return '发送中';
        case '2':
          return '发送成功';
        case '3':
          return '发送失败';
        default:
          return status || '未知';
      }
    }
  }
};
</script>

<style scoped>
/* Add styles similar to SmsBulkTask.vue but for email */
.email-task-container { padding: 0px; }
.card-header { display: flex; justify-content: space-between; align-items: center; }
.header-title { font-size: 16px; font-weight: 600; }
.stat-number { font-weight: bold; }
.stat-number.success { color: #67c23a; }
.stat-number.error { color: #f56c6c; }
.html-preview { margin-top: 20px; }
.preview-box { border: 1px solid #EBEEF5; padding: 10px; margin-top: 10px; border-radius: 4px; max-height: 400px; overflow-y: auto; }
.empty-state { text-align: center; color: #909399; padding-top: 50px; }
.empty-state i { font-size: 50px; margin-bottom: 20px; }

/* 接收者列表样式 */
.recipients-section {
  margin-top: 20px;
  border-top: 1px solid #EBEEF5;
  padding-top: 20px;
}

.section-title {
  display: flex;
  justify-content: space-between;
  align-items: center;
  margin-bottom: 15px;
}

.section-title-left {
  display: flex;
  align-items: center;
  font-size: 16px;
  font-weight: 600;
  color: #303133;
}

.section-title-left i {
  margin-right: 8px;
  color: #409EFF;
}

.recipients-table {
  border-radius: 4px;
  overflow: hidden;
}

.empty-recipients {
  text-align: center;
  padding: 40px 20px;
  color: #909399;
  background-color: #fafafa;
  border-radius: 4px;
  border: 1px dashed #dcdfe6;
}

.empty-recipients i {
  font-size: 32px;
  margin-bottom: 10px;
  display: block;
}

.error-msg {
  color: #f56c6c;
  font-size: 12px;
}

/* 任务详情增强样式 */
.task-detail-header {
  text-align: right;
  margin-bottom: 15px;
}

.send-stats {
  display: flex;
  flex-direction: column;
  gap: 8px;
}

.stat-item {
  display: flex;
  justify-content: space-between;
}

.stat-label {
  color: #606266;
  font-size: 13px;
}

.stat-value {
  font-weight: bold;
  font-size: 13px;
}

.stat-value.success {
  color: #67c23a;
}

.stat-value.error {
  color: #f56c6c;
}
</style>
